package com.smm.web.vmc.controller.admin;

import com.smm.web.vmc.domain.Admin;
import com.smm.web.vmc.dto.JsonReturn;
import com.smm.web.vmc.service.AdminService;
import com.smm.web.vmc.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhenghao on 2016/9/6.
 *
 */
@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;

    @RequestMapping("/alertPwd.do")
    public ModelAndView alertPassword(){

        return new ModelAndView("admin/alertPwd");
    }

    @RequestMapping("/submitAlertPwd.do")
    @ResponseBody
    public JsonReturn submitAlertPwd(HttpServletRequest request,String password,String newPassword){

        //从session中获取管理员信息
        Admin admin = (Admin) request.getSession().getAttribute(AdminService._ADMIN_IN_SESSION);

        try{


            if(StringUtils.isBlank(password)) throw new Exception("原密码不能为空");

            if(StringUtils.isBlank(newPassword)) throw new Exception("新密码不能为空");

            //检查原密码是否正确
            password = MD5Util.parseStrToMd5L32(password);

            log.info("------password:"+password+"    newPasswrod:"+newPassword);


            if(password.equals(admin.getPassword())){

                //保存新密码到数据库
                admin.setPassword(MD5Util.parseStrToMd5L32(newPassword));

                adminService.update(admin);

                return new JsonReturn(1,"修改密码成功");

            }else{

                throw new Exception("原登陆密码不正确");
            }

        }catch (Exception e){

            e.printStackTrace();

            log.error(String.valueOf(e));

            return new JsonReturn(0,"修改密码失败！错误信息:"+e.getMessage());

        }

    }

}
